//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Collections.Generic;
using System.Windows.Data;
using System.Windows.Media;

namespace OpenLS.Drawing.UI.Internals
{
    public class FillPropertiesToBrushConverter: IMultiValueConverter
    {
        static ColorScheme previousColorScheme;
        static Dictionary<FillProperties, Brush> cache = new Dictionary<FillProperties, Brush>();
        public static Brush FillPropertiesToBrush(FillProperties props, ColorScheme colorScheme, StyleMatrixReference styleMatrix)
        {
            if (props == null)
            {
                if (styleMatrix != null)
                    return ColorBaseToBrushConverter.ColorBaseToBrush(styleMatrix.Color, colorScheme);
                return null;
            }
            Brush result;
            if (previousColorScheme != colorScheme)
                cache = new Dictionary<FillProperties, Brush>();
            previousColorScheme = colorScheme;
            if (cache.TryGetValue(props, out result))
                return result;
            result = props.ToBrush(colorScheme);
            cache.Add(props, result);
            return result;
        }

        #region IMultiValueConverter Members

        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            StyleMatrixReference styleMatrix = null;
            if (values.Length == 3)
            {
                styleMatrix = StrictConverter.Convert<StyleMatrixReference>(values[2]);
            }
            var f = StrictConverter.Convert<FillProperties>(values[0]);
            var result =  FillPropertiesToBrush(
                f,
                StrictConverter.Convert<ColorScheme>(values[1]),
                styleMatrix);
            return result;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotSupportedException();
        }

        #endregion
    }
}